<!-- 分类管理 新增/修改 -->
<template>
  <div>
    <el-dialog :title="categoryData.categoryListTitle" :visible.sync="categoryData.showModal" width="700px" top="5vh">
      <el-form label-width="130px" :model="data" ref="update" :rules="rules" v-loading="showLoading" :element-loading-text="$t('lan.dataLoading')">
        <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item :label="$t('lan.superiorColumn')" prop="pid">
              <el-select v-model="data.pid" size="medium" clearable :placeholder="$t('lan.selectColumn')">
                <el-option v-for="item in list" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item :label="$t('lan.columnName')" prop="name">
              <el-input size="medium" :placeholder="$t('lan.pleaseColumnName')" v-model="data.name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item :label="$t('lan.price')" prop="price">
              <el-input size="medium" type="number" :placeholder="$t('lan.pleasePrice')" v-model.number="data.price"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item label="级别" prop="level">
              <el-input size="medium" placeholder="请输入级别" v-model="data.level"></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item :label="$t('lan.uploadImg')" prop="url">
              <el-upload class="upload-demo" :action='fileUrl + "/attachment/fileUpload"' name="uploadFile" :headers="tokenimg" :on-success="onSuccess" :before-upload="beforeUpload" :show-file-list="false">
                <el-button size="small" type="primary">{{$t('lan.clickUpload')}}</el-button>
                <div>
                  <img v-if="data.url" :src="data.url" class="imgbox" />
                </div>
                <div slot="tip" class="el-upload__tip">{{$t('lan.only3MB')}}</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item :label="$t('lan.sort')" prop="sort">
              <el-input size="medium" :placeholder="$t('lan.pleaseSort')" v-model="data.sort"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部按钮开始 -->
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" type="primary" @click="add">{{$t('lan.submit')}}</el-button>
        <el-button size="medium" @click="categoryData.showModal = false">{{$t('lan.cancel')}}</el-button>
      </span>
      <!-- 底部按钮结束 -->
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: ["categoryData"],
  data () {
    // 自定义图片校验
    let valiurl = (rule, value, callback) => {
      if (this.data.url == '') {
        callback(new Error(this.$t('lan.pleaseUpload')));
      } else {
        callback();
      }
    };
    return {
      uploadFile: "", // 图片的文件名称
      tokenimg: { token: sessionStorage.getItem("token") }, // 图片请求头
      typeList: [],
      showLoading: false, //是否显示loading
      title: "", //标题
      //需要提交的数据
      data: {
        id: "",
        name: "",
        sort: "",
        pid: '',
        price: '',
        url: '',
      },
      fileUrl: this.request.server,
      list: [],
      //表单校验
      rules: {
        url: [{ required: true, validator: valiurl, trigger: "change" }],
        // pid: [{ required: true, message: "上级分类不能为空", trigger: "blur" }],
        name: [{ required: true, message: this.$t('lan.cannotEmpty'), trigger: "blur" }],
        price: [{ required: true, message: this.$t('lan.priceEmpty'), trigger: "blur" }],
        // level: [{ required: true, message: "级别不能为空", trigger: "blur" }],
        sort: [{ required: true, message: this.$t('lan.sortEmpty'), trigger: "blur" }]
      }
    };
  },
  methods: {
    // 图片上传成功后，后台返回图片的路径
    onSuccess (res) {
      if (res.code == 200) {
        this.data.url = res.data;
      }
    },
    // 图片校验
    beforeUpload (file) {
      // const isJPG = file.type === 'image/jpeg'
      var testmsg = /^image\/(jpeg|png|jpg)$/.test(file.type);
      const isLt5KB = file.size / 1024 / 1024 < 2;
      if (!testmsg) {
        this.$message.error(this.$t('lan.uploadFormat'));
        return;
      }
      if (!isLt5KB) {
        this.$message.error(this.$t('lan.uploaded2MB'));
      }
      return testmsg && isLt5KB;
    },
    //新增、修改分类
    add () {
      this.$refs["update"].validate(async valid => {
        if (valid) {
          this.showLoading = true;
          let url = this.categoryData.type == "create" ? "/category/save" : "/category/update";
          let httpMethod = this.categoryData.type == "create" ? "POST" : "PUT";
          let result = await this.request.httpRequest(httpMethod, url, this.data);
          if (result.code == 200) {
            this.categoryData.showModal = false;
            this.$message({ type: "success", message: result.msg });
            this.$emit("getRoleList");
          } else {
            this.$message({ type: "error", message: result.msg });
          }
          this.showLoading = false;
        }
      });
    },
    // 获取上级列表
    async getList () {
      const url = '/category/queryList'
      const result = await this.request.httpRequest('POST', url, { pid: 0 });
      if (result.code === 200) {
        this.list = result.data
      }
    },
    //获取详情
    async getDetail () {
      if (this.categoryData.roleId) {
        let url = `/category/get/${this.categoryData.roleId}`;
        let result = await this.request.httpRequest("GET", url);
        if (result.code == 200) {
          this.data.pid = result.data.pid;
          this.data.name = result.data.name;
          this.data.sort = result.data.sort;
          this.data.price = result.data.price;
          this.data.id = result.data.id
          this.data.url = result.data.url;
        } else {
          this.$message({ type: "error", message: result.msg });
        }
      }
    }
  },
  mounted () {
    this.getList();
    this.getDetail();

  }
};
</script>
